package mylab.io.core.codec;

import com.google.common.base.Preconditions;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import mylab.io.base.model.Msg;
import mylab.utils.common.CastUtil;

@ChannelHandler.Sharable
public class SimpleEncoder<M extends Msg> extends MessageToMessageEncoder<Msg> {
    public static final String HANDLER_NAME = SimpleEncoder.class.getSimpleName();

    protected MsgResolver<M, ByteBuf> msgResolver;

    public SimpleEncoder(MsgResolver<M, ByteBuf> msgResolver) {
        Preconditions.checkNotNull(msgResolver);
        this.msgResolver = msgResolver;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Msg msg, List<Object> out) throws Exception {
        M m = CastUtil.cast(msg);
        ByteBuf buf = msgResolver.down(m);
        out.add(buf);
    }
}